package com.atguigu.gmall.order.contorller;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    OrderService orderService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignClient productFeignClient;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;


    // /api/order/auth/trade
    @GetMapping("/auth/trade")
    public Result<Map<String,Object>> trade(HttpServletRequest request){
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //获取用户地址
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        //获取购物车得商品
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);


        AtomicInteger totalNum = new AtomicInteger();
        List<OrderDetail> orderDetailList = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setOrderPrice(cartInfo.getCartPrice());

            //计算数据
            totalNum.addAndGet(cartInfo.getSkuNum());

            return orderDetail;
        }).collect(Collectors.toList());

        OrderInfo orderInfo = new OrderInfo();

        orderInfo.setOrderDetailList(orderDetailList);

        orderInfo.sumTotalAmount();

        //  获取流水号,同时还将流水号放入了缓存.
        String tradeNo = this.orderService.getTradeNo(userId);

        Map<String,Object> hashmap = new HashMap<>();
        hashmap.put("userAddressList",userAddressList);
        hashmap.put("detailArrayList",orderDetailList);
        hashmap.put("totalNum",totalNum);
        hashmap.put("totalAmount",orderInfo.getTotalAmount());
        //  存储流水号。
        hashmap.put("tradeNo",tradeNo);
        return Result.ok(hashmap);
    }

    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,
                              HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //获取流水号
        String tradeNo = request.getParameter("tradeNo");
        //调用比较方法
        Boolean result = this.orderService.checkTradeNo(userId, tradeNo);
        if(!result){
            return Result.fail().message("不能无刷新重复提交订单");
        }
        //删除缓存了流水号
        this.orderService.delTradeNo(userId);

        ArrayList<CompletableFuture> completableFutureArrayList = new ArrayList<>();
        ArrayList<String> errorList = new ArrayList<>();
        //验证库存
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                Boolean result1 = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                if (!result1) {
                    //记录当前信息
                    errorList.add(orderDetail.getSkuNum() + "库存不足");
                }
            },threadPoolExecutor);
            //添加到集合中
            completableFutureArrayList.add(stockCompletableFuture);

            CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {
                //验证价格
                BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                if (orderDetail.getOrderPrice().compareTo(skuPrice) != 0) {
                    List<CartInfo> cartCheckedList = this.cartFeignClient.getCartCheckedList(userId);
                    cartCheckedList.forEach(cartInfo -> {
                        this.redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);
                    });
                    errorList.add(orderDetail.getSkuName() + "价格有变动");
                }
            },threadPoolExecutor);
            completableFutureArrayList.add(priceCompletableFuture);
        }

        CompletableFuture.allOf(completableFutureArrayList.toArray(new CompletableFuture[completableFutureArrayList.size()])).join();
        //判断线程返回值是否有问题
        if(errorList.size()>0){
            return Result.fail().message(StringUtils.join(errorList,","));
        }
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return Result.ok(orderId);
    }

    //显示订单
    @GetMapping("auth/{page}/{limit}")
    public Result<IPage<OrderInfo>> index(@PathVariable Long page,
                                          @PathVariable Long limit,
                                          HttpServletRequest request){

        String userId = AuthContextHolder.getUserId(request);
        Page<OrderInfo> pageParam = new Page<>(page,limit);

        IPage<OrderInfo> pageModel = orderService.getpage(pageParam,userId);
        return Result.ok(pageModel);
    }
    /**
    // * 内部调用获取订单
    //  * @param orderId
    // * @return
    // */
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderService.getOrderInfo(orderId);
    }

    //拆单接口
    @PostMapping("orderSplit")
    public String orderSplit(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");

        List<OrderInfo> orderInfoList = orderService.orderSplit(Long.parseLong(orderId), wareSkuMap);
        ArrayList<Map> mapArrayList = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfoList) {
            Map map = orderService.initWareOrder(orderInfo);
            mapArrayList.add(map);
        }
        return JSON.toJSONString(mapArrayList);
    }
    @PostMapping("inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo){
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return orderId;
    }

}
